package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.RegionQuery;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
//@Transactional  暂时先别管事务
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private RegionRepository repository;

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return repository.findAll();
    }

    @Override
    public void save(Region region) {
        region.setId(null);
        repository.save(region);
    }

    @Override
    public void update(Region region) {
        repository.save(region);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        //条件
        Query query = new Query();
        //总条数
        long count = template.count(query, Region.class);
        if(count==0){
            return Page.empty();
        }
        //页面显示数据集合
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "_id");
        query.with(pageable);
        List<Region> list = template.find(query, Region.class);
        return new PageImpl<>(list,pageable,count);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if(StringUtils.hasLength(region.getId())){
            this.update(region);
        }else {
            this.save(region);
        }
    }

    @Override
    public void changeHotValue(String id, int hot) {
        Region region = this.get(id);
        region.setIshot(hot);
        this.update(region);
    }
}
